﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExternalConnections.CApECExternalConnectionsManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using C1.Win.C1FlexGrid;
using C1.Win.C1FlexGrid.Util.BaseControls;
using DnProcessSimulateCommands.ExternalConnections.Res;
using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ExternalConnections;

public class CApECExternalConnectionsManager
{
  internal const string LOCAL_SERVER_PATH = "local";
  internal const string LOCAL_HOST_SERVER_PATH = "localhost";
  public const string EXCEL_EXPORT_DEFAULT_FILE_NAME = "External_Connections.xls";
  internal const string MAP_SIGNAL_BY_HARDCODED_SERVER_ADDRESS = "Server address";
  internal const string MAP_SIGNAL_BY_HARDCODED_SIGNAL_NAME = "Signal name";
  internal const string COL_HARDCODED_NAME = "Name";
  internal const string COL_HARDCODED_TYPE = "Type";
  internal const string COL_HARDCODED_OPC_SERVER = "Server";
  internal const string COL_HARDCODED_ITEM_HEADER = "Item Header";
  internal const string COL_HARDCODED_NAME_SPACE_INDEX = "NameSpace Index";
  internal const string COL_HARDCODED_PLC_PROGRAM_PATH = "Plc Program Path";
  internal const string COL_HARDCODED_INSTANCE_NAME = "Instance Name";
  internal const string COL_HARDCODED_COM_ELEMENT = "Communication Element";
  internal const string COL_HARDCODED_MAP_SIGNALS_BY = "Map Signals By";
  internal const string COL_HARDCODED_PLUGIN_STATE = "Plug-in State";
  internal const string COL_HARDCODED_TAG_ACCESS_MODE = "Tag Access Mode";
  private Dictionary<string, CApECExternalConnectionNode> m_opcIdToNodeMap = new Dictionary<string, CApECExternalConnectionNode>();
  private Dictionary<string, string> m_plcimAdvancedConnctionMap = new Dictionary<string, string>();
  private Dictionary<string, string> m_winModConnctionMap = new Dictionary<string, string>();
  private Dictionary<string, string> m_simitCouplingConnectionMap = new Dictionary<string, string>();
  private Dictionary<string, string> m_userDefinedConnectionMap = new Dictionary<string, string>();
  private CUiECExternalConnectionsGridWrapper m_grid;
  private const string KEY_SEPARATOR = "|";

  public CApECExternalConnectionsManager(CUiECExternalConnectionsGridWrapper grid)
  {
    this.m_grid = grid;
  }

  internal bool ExistConnectionNodes => this.m_opcIdToNodeMap.Count > 0;

  public List<TxPlcExternalConnectionEx> Connections
  {
    get
    {
      List<TxPlcExternalConnectionEx> connections = new List<TxPlcExternalConnectionEx>();
      foreach (CApECExternalConnectionNode connectionNode in this.m_grid.ConnectionNodes)
        connections.Add(connectionNode.Connection);
      return connections;
    }
  }

  public TxPlcExternalConnectionEx GetConnectionByName(string connectionName)
  {
    TxPlcExternalConnectionEx connectionByName = (TxPlcExternalConnectionEx) null;
    foreach (CApECExternalConnectionNode node in this.m_grid.Nodes)
    {
      if (node.Connection.Data.Name == connectionName)
      {
        connectionByName = node.Connection;
        break;
      }
    }
    return connectionByName;
  }

  internal List<TxPlcExternalConnectionEx> SelectedConnections
  {
    get
    {
      List<TxPlcExternalConnectionEx> selectedConnections = new List<TxPlcExternalConnectionEx>();
      foreach (CApECExternalConnectionNode selectedConnectionNode in this.m_grid.SelectedConnectionNodes)
        selectedConnections.Add(selectedConnectionNode.Connection);
      return selectedConnections;
    }
  }

  internal CApECExternalConnectionNode ConnectionNode(TxPlcExternalConnectionEx connection)
  {
    return this.CreateConnectionNode(connection);
  }

  internal bool DoesExistConnectionWithName(string name)
  {
    return TxApplicationEx.ExternalConnectionsManager().ConnectionNames.Contains(name);
  }

  internal bool CanCreateConnectionWithData(
    ITxPlcExternalConnectionDataEx creationData,
    out CApECExternalConnectionsManager.eCreateConnectionFailiureReason failiureReason)
  {
    failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.None;
    bool connectionWithData = !this.DoesExistConnectionWithName(creationData.Name);
    if (!connectionWithData)
      failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedName;
    if (connectionWithData)
    {
      if (creationData is TxPlcSimitCouplingConnectionDataEx && this.IsSimitCouplingConnectionExists((ITxPlcExternalConnectionDataEx) (creationData as TxPlcSimitCouplingConnectionDataEx)))
      {
        connectionWithData = false;
        failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedKey;
      }
      if (creationData is TxPlcUserDefinedConnectionDataEx)
      {
        if (this.IsUserDefinedConnectionExists((ITxPlcExternalConnectionDataEx) (creationData as TxPlcUserDefinedConnectionDataEx)))
        {
          connectionWithData = false;
          failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedKey;
        }
      }
      else if (creationData is TxPlcSimAdvConnectionDataEx)
      {
        if (this.IsPlcSimAdvancedConnectionExists((ITxPlcExternalConnectionDataEx) (creationData as TxPlcSimAdvConnectionDataEx)))
        {
          connectionWithData = false;
          failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedKey;
        }
      }
      else if (creationData is TxPlcWinModConnectionDataEx && this.IsWinModConnectionExists((ITxPlcExternalConnectionDataEx) (creationData as TxPlcWinModConnectionDataEx)))
      {
        connectionWithData = false;
        failiureReason = CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedKey;
      }
    }
    return connectionWithData;
  }

  internal bool CanSetConnectionData(
    TxPlcExternalConnectionEx connection,
    ITxPlcExternalConnectionDataEx data,
    out CApECExternalConnectionsManager.eSetConnectionDataFailiureReason failiureReason)
  {
    failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.None;
    string name = data.Name;
    bool flag;
    if (name == connection.Data.Name)
    {
      flag = true;
    }
    else
    {
      flag = !this.DoesExistConnectionWithName(name);
      if (!flag)
        failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedName;
    }
    if (flag)
    {
      if (data is TxPlcSimitCouplingConnectionDataEx && connection.Data is TxPlcSimitCouplingConnectionDataEx)
      {
        TxPlcSimitCouplingConnectionDataEx data1 = connection.Data as TxPlcSimitCouplingConnectionDataEx;
        TxPlcSimitCouplingConnectionDataEx data2 = data as TxPlcSimitCouplingConnectionDataEx;
        if (!this.formatSimitCouplingKey(data1).Equals(this.formatSimitCouplingKey(data2)) && this.IsSimitCouplingConnectionExists((ITxPlcExternalConnectionDataEx) data2))
        {
          flag = false;
          failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedKey;
        }
      }
      if (data is TxPlcUserDefinedConnectionDataEx && connection.Data is TxPlcUserDefinedConnectionDataEx)
      {
        TxPlcUserDefinedConnectionDataEx data3 = connection.Data as TxPlcUserDefinedConnectionDataEx;
        TxPlcUserDefinedConnectionDataEx data4 = data as TxPlcUserDefinedConnectionDataEx;
        if (!this.formatUserDefinedKey(data3).Equals(this.formatUserDefinedKey(data4)) && this.IsUserDefinedConnectionExists((ITxPlcExternalConnectionDataEx) data4))
        {
          flag = false;
          failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedKey;
        }
      }
      else if (data is TxPlcSimAdvConnectionDataEx && connection.Data is TxPlcSimAdvConnectionDataEx)
      {
        TxPlcSimAdvConnectionDataEx data5 = connection.Data as TxPlcSimAdvConnectionDataEx;
        TxPlcSimAdvConnectionDataEx data6 = data as TxPlcSimAdvConnectionDataEx;
        if (!this.formatPlcismAdvancedKey(data5).Equals(this.formatPlcismAdvancedKey(data6)) && this.IsPlcSimAdvancedConnectionExists((ITxPlcExternalConnectionDataEx) data6))
        {
          flag = false;
          failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedKey;
        }
      }
      else if (data is TxPlcWinModConnectionDataEx && connection.Data is TxPlcWinModConnectionDataEx)
      {
        TxPlcWinModConnectionDataEx data7 = connection.Data as TxPlcWinModConnectionDataEx;
        TxPlcWinModConnectionDataEx data8 = data as TxPlcWinModConnectionDataEx;
        if (!this.formatWinModKey(data7).Equals(this.formatWinModKey(data8)) && this.IsWinModConnectionExists((ITxPlcExternalConnectionDataEx) data8))
        {
          flag = false;
          failiureReason = CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedKey;
        }
      }
    }
    return flag;
  }

  internal void Initialize() => this.RegisterForEvents();

  internal void UnInitialize()
  {
    this.Clear();
    this.UnregisterForEvents();
  }

  internal bool Load()
  {
    bool flag = true;
    ((ScrollableControl) this.m_grid).BeginUpdate();
    try
    {
      this.Clear();
      ((C1FlexGridBase) this.m_grid).Select(-1, -1);
      List<TxPlcExternalConnectionEx> connections = TxApplicationEx.ExternalConnectionsManager().Connections;
      connections.Sort(new Comparison<TxPlcExternalConnectionEx>(this.ConnectionsComparison_AscendingName));
      foreach (TxPlcExternalConnectionEx connection in connections)
      {
        if (this.AddConnectionNode(connection) == null)
        {
          flag = false;
          break;
        }
      }
    }
    finally
    {
      ((ScrollableControl) this.m_grid).EndUpdate();
    }
    return flag;
  }

  internal void Clear()
  {
    this.m_opcIdToNodeMap.Clear();
    this.m_grid.RemoveConnectionNodes(this.m_grid.ConnectionNodes);
  }

  private int ConnectionsComparison_AscendingName(
    TxPlcExternalConnectionEx first,
    TxPlcExternalConnectionEx second)
  {
    return first.Data.Name.CompareTo(second.Data.Name);
  }

  public CApECExternalConnectionNode CreateConnection(
    ITxPlcExternalConnectionDataEx creationData,
    out CApECExternalConnectionsManager.eCreateConnectionFailiureReason failiureReason)
  {
    CApECExternalConnectionNode connection1 = (CApECExternalConnectionNode) null;
    if (this.CanCreateConnectionWithData(creationData, out failiureReason))
    {
      TxPlcExternalConnectionEx connection2 = TxApplicationEx.ExternalConnectionsManager().CreateConnection(creationData);
      if (connection2 != null)
        connection1 = this.AddConnectionNode(connection2);
    }
    return connection1;
  }

  internal bool SetConnectionData(
    TxPlcExternalConnectionEx connection,
    ITxPlcExternalConnectionDataEx data,
    out CApECExternalConnectionsManager.eSetConnectionDataFailiureReason failiureReason)
  {
    bool flag = false;
    if (this.CanSetConnectionData(connection, data, out failiureReason))
    {
      if (data.ConnectionType == null)
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcOpcConnectionDataEx);
      else if (data.ConnectionType == 2)
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcOpcUAConnectionDataEx);
      else if (data.ConnectionType == 1)
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcSimbaConnectionDataEx);
      else if (data.ConnectionType == 3)
      {
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcSimAdvConnectionDataEx);
        this.UpdatePlcSimAdvancedFilter(connection);
      }
      else if (data.ConnectionType == 4)
      {
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcWinModConnectionDataEx);
        this.UpdateWinModFilter(connection);
      }
      else if (data.ConnectionType == 5)
      {
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcSimitCouplingConnectionDataEx);
        this.UpdateSimitCouplingFilter(connection);
      }
      else if (data.ConnectionType == 6)
      {
        connection.Data = (ITxPlcExternalConnectionDataEx) (data as TxPlcUserDefinedConnectionDataEx);
        this.UpdateUserDefinedFilter(connection);
      }
      string id = connection.Id;
      if (this.m_opcIdToNodeMap.ContainsKey(id))
      {
        this.m_grid.UpdateNode((CApECBaseNode) this.m_opcIdToNodeMap[id]);
        flag = true;
      }
    }
    return flag;
  }

  public bool RemoveConnection(TxPlcExternalConnectionEx connection)
  {
    string id = connection.Id;
    bool flag = this.RemoveConnectionNode(connection);
    TxApplicationEx.ExternalConnectionsManager().RemoveConnection(connection);
    return flag;
  }

  public bool RemoveConnections(List<TxPlcExternalConnectionEx> connections)
  {
    bool flag = true;
    if (connections.Count > 0)
    {
      ((ScrollableControl) this.m_grid).BeginUpdate();
      try
      {
        foreach (TxPlcExternalConnectionEx connection in connections)
        {
          if (!this.RemoveConnection(connection))
          {
            flag = false;
            break;
          }
        }
      }
      finally
      {
        ((ScrollableControl) this.m_grid).EndUpdate();
      }
    }
    return flag;
  }

  public void ValidateConnections(
    List<TxPlcExternalConnectionEx> connections,
    out ValidateConnectionsOutputParams outputParams)
  {
    outputParams = (ValidateConnectionsOutputParams) null;
    List<TxPlcExternalConnectionEx> validConnections = new List<TxPlcExternalConnectionEx>(connections.Count);
    List<TxPlcExternalConnectionEx> invalidConnections = new List<TxPlcExternalConnectionEx>(connections.Count);
    List<string> invalidConnectionsReason = new List<string>();
    List<bool> boolList;
    List<string> stringList;
    TxApplicationEx.ExternalConnectionsManager().ValidateConnections(connections, ref boolList, ref stringList);
    for (int index = 0; index < boolList.Count; ++index)
    {
      if (boolList[index])
      {
        validConnections.Add(connections[index]);
      }
      else
      {
        invalidConnections.Add(connections[index]);
        invalidConnectionsReason.Add(stringList[index]);
      }
    }
    outputParams = new ValidateConnectionsOutputParams(validConnections, invalidConnections, invalidConnectionsReason);
  }

  public void ValidateExternalConnection(
    TxPlcExternalConnectionEx connection,
    out ValidateConnectionsOutputParams outputParams)
  {
    outputParams = (ValidateConnectionsOutputParams) null;
    if (connection == null)
      return;
    this.ValidateConnections(new List<TxPlcExternalConnectionEx>()
    {
      connection
    }, out outputParams);
  }

  internal void ValidateConnections(List<TxPlcExternalConnectionEx> connections)
  {
    if (connections.Count <= 0)
      return;
    ValidateConnectionsOutputParams outputParams = (ValidateConnectionsOutputParams) null;
    this.ValidateConnections(connections, out outputParams);
    this.CreateErrorMassage(connections, outputParams);
  }

  internal void CreateErrorMassage(
    List<TxPlcExternalConnectionEx> connections,
    ValidateConnectionsOutputParams outputParams)
  {
    if (outputParams == null)
      return;
    bool flag1 = outputParams.InvalidConnections != null && outputParams.InvalidConnections.Count > 0;
    bool flag2 = outputParams.ValidConnections != null && outputParams.ValidConnections.Count > 0;
    string connectionsCaption = CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_CAPTION;
    string str1 = (string) null;
    string str2 = Environment.NewLine + Environment.NewLine;
    if (flag2)
    {
      if (flag1)
      {
        string invalidConnections = this.GenerateMessageForInvalidConnections(outputParams);
        str1 = CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_INVALID_PARTIAL + str2 + invalidConnections;
      }
      else
        str1 = outputParams.ValidConnections.Count != 1 ? CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_VALID_MULTI : CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_VALID_SINGLE;
    }
    else if (flag1)
    {
      string invalidConnections = this.GenerateMessageForInvalidConnections(outputParams);
      str1 = outputParams.InvalidConnections.Count != 1 ? CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_INVALID_MULTI + str2 + invalidConnections : CUiECExternalConnectionsResourceTable.MSG_VALIDATE_CONNECTIONS_INVALID_SINGLE + str2 + invalidConnections;
    }
    MessageBoxIcon messageBoxIcon = flag1 ? MessageBoxIcon.Hand : MessageBoxIcon.None;
    int num = (int) TxMessageBox.ShowModal(str1, connectionsCaption, MessageBoxButtons.OK, messageBoxIcon);
  }

  private string GenerateMessageForInvalidConnections(ValidateConnectionsOutputParams outputParams)
  {
    int count = outputParams.InvalidConnections.Count;
    if (count < 1)
      return string.Empty;
    if (count == 1)
      return $"'{outputParams.InvalidConnections[0].Data.Name}' - {outputParams.InvalidConnectionsReason[0]}";
    string str1 = new string('-', 30);
    Dictionary<string, List<int>> dictionary = new Dictionary<string, List<int>>();
    for (int index = 0; index < count; ++index)
    {
      TxPlcExternalConnectionEx invalidConnection = outputParams.InvalidConnections[index];
      string key = outputParams.InvalidConnectionsReason[index];
      if (dictionary.ContainsKey(key))
        dictionary[key].Add(index);
      else
        dictionary.Add(key, new List<int>(1) { index });
    }
    StringBuilder stringBuilder1 = new StringBuilder();
    for (int index1 = 0; index1 < count; ++index1)
    {
      TxPlcExternalConnectionEx invalidConnection = outputParams.InvalidConnections[index1];
      string key = outputParams.InvalidConnectionsReason[index1];
      if (dictionary.ContainsKey(key))
      {
        string str2 = (string) null;
        int length = key.IndexOf(Environment.NewLine);
        string str3;
        if (length < 0)
        {
          str3 = key;
        }
        else
        {
          str3 = key.Substring(0, length);
          str2 = key.Substring(length + Environment.NewLine.Length);
        }
        if (stringBuilder1.Length > 0)
        {
          stringBuilder1.AppendLine();
          stringBuilder1.AppendLine(str1);
        }
        List<int> intList = dictionary[key];
        StringBuilder stringBuilder2 = new StringBuilder();
        foreach (int index2 in intList)
        {
          if (stringBuilder2.Length > 0)
            stringBuilder2.Append(", ");
          stringBuilder2.Append($"'{outputParams.InvalidConnections[index2].Data.Name}'");
        }
        stringBuilder1.Append($"{stringBuilder2.ToString()} - {str3}");
        if (!string.IsNullOrWhiteSpace(str2))
        {
          stringBuilder1.AppendLine();
          stringBuilder1.Append(str2);
        }
        dictionary.Remove(key);
      }
    }
    return stringBuilder1.ToString();
  }

  public bool ExportConnections(string forceExportPath = null)
  {
    bool flag = false;
    CApECExcelExportParams exportParams = this.PrepareExportParams();
    if (exportParams != null)
      flag = new CApECExcelExportManager().Export(exportParams, forceExportPath);
    return flag;
  }

  public bool ImportConnections(
    out CApECExternalConnectionsManager.ImportOutputParams importOutput,
    string forceImportPath = null)
  {
    bool flag = false;
    importOutput = (CApECExternalConnectionsManager.ImportOutputParams) null;
    CApECExcelImportParams excelImportParams = this.PrepareImportParams();
    if (excelImportParams != null)
    {
      flag = new CApECExcelImportManager().Import(excelImportParams, forceImportPath);
      if (flag)
        flag = this.ProcessImportedConnections(excelImportParams, out importOutput);
      else
        importOutput = new CApECExternalConnectionsManager.ImportOutputParams(excelImportParams);
    }
    return flag;
  }

  private string formatPlcismAdvancedKey(TxPlcSimAdvConnectionDataEx data)
  {
    string str;
    if (data.LocalConnection)
      str = $"{data.EndpointName}|{this.FormatEndpointUrlToIP(data.EndpointUrl)}";
    else
      str = $"{data.EndpointName}|{this.FormatEndpointUrlToIP(data.EndpointUrl)}|{data.Port.ToString()}";
    return str;
  }

  private string formatWinModKey(TxPlcWinModConnectionDataEx data)
  {
    return $"{data.EndpointName}|{data.EndpointUrl}|{data.Port.ToString()}";
  }

  private string formatSimitCouplingKey(TxPlcSimitCouplingConnectionDataEx data)
  {
    return $"{data.EndpointName}|{data.EndpointUrl}";
  }

  private string formatUserDefinedKey(TxPlcUserDefinedConnectionDataEx data)
  {
    return $"{data.COMElement}|{data.EndpointUrl}";
  }

  private CApECExternalConnectionNode CreateConnectionNode(TxPlcExternalConnectionEx connection)
  {
    string key1 = connection.Id;
    if (connection.Data is TxPlcSimAdvConnectionDataEx)
    {
      string key2 = this.formatPlcismAdvancedKey(connection.Data as TxPlcSimAdvConnectionDataEx);
      if (this.m_plcimAdvancedConnctionMap.ContainsKey(key2))
        key1 = this.m_plcimAdvancedConnctionMap[key2];
      else
        this.m_plcimAdvancedConnctionMap.Add(key2, key1);
    }
    if (connection.Data is TxPlcWinModConnectionDataEx)
    {
      string key3 = this.formatWinModKey(connection.Data as TxPlcWinModConnectionDataEx);
      if (this.m_winModConnctionMap.ContainsKey(key3))
        key1 = this.m_winModConnctionMap[key3];
      else
        this.m_winModConnctionMap.Add(key3, key1);
    }
    if (connection.Data is TxPlcSimitCouplingConnectionDataEx data1)
    {
      string key4 = this.formatSimitCouplingKey(data1);
      if (this.m_simitCouplingConnectionMap.ContainsKey(key4))
        key1 = this.m_simitCouplingConnectionMap[key4];
      else
        this.m_simitCouplingConnectionMap.Add(key4, key1);
    }
    if (connection.Data is TxPlcUserDefinedConnectionDataEx data2)
    {
      string key5 = this.formatUserDefinedKey(data2);
      if (this.m_userDefinedConnectionMap.ContainsKey(key5))
        key1 = this.m_userDefinedConnectionMap[key5];
      else
        this.m_userDefinedConnectionMap.Add(key5, key1);
    }
    CApECExternalConnectionNode connectionNode = (CApECExternalConnectionNode) null;
    if (this.m_opcIdToNodeMap.ContainsKey(key1))
      connectionNode = this.m_opcIdToNodeMap[key1];
    return connectionNode;
  }

  private CApECExternalConnectionNode AddConnectionNode(TxPlcExternalConnectionEx connection)
  {
    CApECExternalConnectionNode node = this.CreateConnectionNode(connection);
    if (node == null)
    {
      node = new CApECExternalConnectionNode(connection);
      if (this.m_grid.InsertNode((CApECBaseNode) node, ((RowColCollection) ((C1FlexGridBase) this.m_grid).Rows).Count) != null)
        this.m_opcIdToNodeMap.Add(node.Connection.Id, node);
      else
        node = (CApECExternalConnectionNode) null;
    }
    return node;
  }

  private bool RemoveConnectionNode(TxPlcExternalConnectionEx connection)
  {
    bool flag = false;
    CApECExternalConnectionNode connectionNode = this.CreateConnectionNode(connection);
    if (connectionNode != null)
    {
      this.m_grid.RemoveNode((CApECBaseNode) connectionNode);
      this.m_opcIdToNodeMap.Remove(connection.Id);
      if (connection.Data is TxPlcSimAdvConnectionDataEx)
        this.m_plcimAdvancedConnctionMap.Remove(this.formatPlcismAdvancedKey(connection.Data as TxPlcSimAdvConnectionDataEx));
      else if (connection.Data is TxPlcWinModConnectionDataEx)
        this.m_winModConnctionMap.Remove(this.formatWinModKey(connection.Data as TxPlcWinModConnectionDataEx));
      else if (connection.Data is TxPlcSimitCouplingConnectionDataEx)
        this.m_simitCouplingConnectionMap.Remove(this.formatSimitCouplingKey(connection.Data as TxPlcSimitCouplingConnectionDataEx));
      else if (connection.Data is TxPlcUserDefinedConnectionDataEx)
        this.m_userDefinedConnectionMap.Remove(this.formatUserDefinedKey(connection.Data as TxPlcUserDefinedConnectionDataEx));
      flag = true;
    }
    return flag;
  }

  private CApECExcelExportParams PrepareExportParams()
  {
    CApECExcelExportParams excelExportParams = new CApECExcelExportParams();
    excelExportParams.BrowseDialogTitle = CUiECExternalConnectionsResourceTable.EXPORT_TO_EXCEL_CAPTION;
    excelExportParams.ColumnTypeToColDataMap = new Dictionary<CApECGeneralUtils.eColumnDataType, CApECExcelBaseParams.ColData>(((RowColCollection) ((C1FlexGridBase) this.m_grid).Cols).Count);
    foreach (RowCol col in (IEnumerable) ((C1FlexGridBase) this.m_grid).Cols)
    {
      object obj = this.m_grid.ColumnDataAt(col.Index);
      if (obj != null && obj.GetType() == typeof (CApECGeneralUtils.eColumnDataType))
      {
        CApECGeneralUtils.eColumnDataType key = (CApECGeneralUtils.eColumnDataType) obj;
        string caption = (string) null;
        bool mandatory = true;
        switch (key)
        {
          case CApECGeneralUtils.eColumnDataType.Name:
            caption = "Name";
            break;
          case CApECGeneralUtils.eColumnDataType.Type:
            caption = "Type";
            break;
          case CApECGeneralUtils.eColumnDataType.OpcServer:
            caption = "Server";
            break;
          case CApECGeneralUtils.eColumnDataType.ItemHeader:
            caption = "Item Header";
            break;
          case CApECGeneralUtils.eColumnDataType.NameSpaceIndex:
            caption = "NameSpace Index";
            break;
          case CApECGeneralUtils.eColumnDataType.InstanceName:
            caption = "Instance Name";
            break;
          case CApECGeneralUtils.eColumnDataType.COMElement:
            caption = "Communication Element";
            break;
          case CApECGeneralUtils.eColumnDataType.MapSignalsBy:
            caption = "Map Signals By";
            break;
        }
        CApECExcelBaseParams.ColData colData = new CApECExcelBaseParams.ColData(caption, mandatory);
        excelExportParams.ColumnTypeToColDataMap.Add(key, colData);
      }
    }
    CApECExcelBaseParams.ColData colData1 = new CApECExcelBaseParams.ColData("Plug-in State", false);
    excelExportParams.ColumnTypeToColDataMap.Add(CApECGeneralUtils.eColumnDataType.PluginState, colData1);
    CApECExcelBaseParams.ColData colData2 = new CApECExcelBaseParams.ColData("Tag Access Mode", false);
    excelExportParams.ColumnTypeToColDataMap.Add(CApECGeneralUtils.eColumnDataType.TagAccessMode, colData2);
    excelExportParams.DefaultFileName = "External_Connections.xls";
    List<TxPlcExternalConnectionEx> connections = this.Connections;
    excelExportParams.DataListToExport = new List<ITxPlcExternalConnectionDataEx>(connections.Count);
    foreach (TxPlcExternalConnectionEx externalConnectionEx in connections)
      excelExportParams.DataListToExport.Add(externalConnectionEx.Data);
    return excelExportParams;
  }

  private CApECExcelImportParams PrepareImportParams()
  {
    CApECExcelImportParams excelImportParams = new CApECExcelImportParams();
    excelImportParams.BrowseDialogTitle = CUiECExternalConnectionsResourceTable.IMPORT_FROM_EXCEL_CAPTION;
    excelImportParams.DataConvertor = (IApECExternalConnectionDataConvertor) new CApECExternalConnectionDataExportConvertor();
    excelImportParams.ColumnTypeToColDataMap = new Dictionary<CApECGeneralUtils.eColumnDataType, CApECExcelBaseParams.ColData>(((RowColCollection) ((C1FlexGridBase) this.m_grid).Cols).Count);
    foreach (RowCol col in (IEnumerable) ((C1FlexGridBase) this.m_grid).Cols)
    {
      object obj = this.m_grid.ColumnDataAt(col.Index);
      if (obj != null && obj.GetType() == typeof (CApECGeneralUtils.eColumnDataType))
      {
        CApECGeneralUtils.eColumnDataType key = (CApECGeneralUtils.eColumnDataType) obj;
        string caption = (string) null;
        bool mandatory = true;
        switch (key)
        {
          case CApECGeneralUtils.eColumnDataType.Name:
            caption = "Name";
            break;
          case CApECGeneralUtils.eColumnDataType.Type:
            caption = "Type";
            mandatory = false;
            break;
          case CApECGeneralUtils.eColumnDataType.OpcServer:
            caption = "Server";
            break;
          case CApECGeneralUtils.eColumnDataType.ItemHeader:
            caption = "Item Header";
            break;
          case CApECGeneralUtils.eColumnDataType.NameSpaceIndex:
            caption = "NameSpace Index";
            break;
          case CApECGeneralUtils.eColumnDataType.InstanceName:
            caption = "Instance Name";
            break;
          case CApECGeneralUtils.eColumnDataType.COMElement:
            caption = "Communication Element";
            break;
          case CApECGeneralUtils.eColumnDataType.MapSignalsBy:
            caption = "Map Signals By";
            break;
        }
        CApECExcelBaseParams.ColData colData = new CApECExcelBaseParams.ColData(caption, mandatory);
        excelImportParams.ColumnTypeToColDataMap.Add(key, colData);
      }
    }
    CApECExcelBaseParams.ColData colData1 = new CApECExcelBaseParams.ColData("Plug-in State", false);
    excelImportParams.ColumnTypeToColDataMap.Add(CApECGeneralUtils.eColumnDataType.PluginState, colData1);
    CApECExcelBaseParams.ColData colData2 = new CApECExcelBaseParams.ColData("Tag Access Mode", false);
    excelImportParams.ColumnTypeToColDataMap.Add(CApECGeneralUtils.eColumnDataType.TagAccessMode, colData2);
    excelImportParams.ClearOutput();
    return excelImportParams;
  }

  private List<string> ParseImportedConnections(CApECExcelImportParams xlImportParams)
  {
    List<string> importedConnections = new List<string>();
    for (int index = 0; index < xlImportParams.ImportedDataList.Count; ++index)
    {
      int num1 = -1;
      int num2 = index + 2;
      ITxPlcExternalConnectionDataEx importedData = xlImportParams.ImportedDataList[index];
      if (index < xlImportParams.ImportedDataList.Count - 1)
        num1 = this.FindIdenticalDataIndexByFilter(importedData, CApECExternalConnectionsManager.eConnectionDataFilterFlags.Name, xlImportParams.ImportedDataList, index + 1);
      if (num1 >= 0)
      {
        string str = string.Format(CUiECExternalConnectionsResourceTable.LOG_FILE_DUPLICATED_NAME, (object) importedData.Name, (object) num2);
        importedConnections.Add(str);
      }
    }
    return importedConnections;
  }

  private bool ProcessImportedConnections(
    CApECExcelImportParams xlImportParams,
    out CApECExternalConnectionsManager.ImportOutputParams outputParams)
  {
    bool flag1 = true;
    outputParams = (CApECExternalConnectionsManager.ImportOutputParams) null;
    if (xlImportParams.ImportFailed || xlImportParams.ImportedDataList == null || xlImportParams.ImportedDataList.Count == 0)
    {
      outputParams = new CApECExternalConnectionsManager.ImportOutputParams(xlImportParams);
    }
    else
    {
      List<string> importedConnections = this.ParseImportedConnections(xlImportParams);
      outputParams = new CApECExternalConnectionsManager.ImportOutputParams(xlImportParams, importedConnections);
      if (importedConnections.Count > 0)
        flag1 = false;
      if (flag1)
      {
        List<TxPlcExternalConnectionEx> connections = this.Connections;
        List<ITxPlcExternalConnectionDataEx> list = new List<ITxPlcExternalConnectionDataEx>(connections.Count);
        foreach (TxPlcExternalConnectionEx externalConnectionEx in connections)
          list.Add(externalConnectionEx.Data);
        List<ITxPlcExternalConnectionDataEx> connectionDataExList = new List<ITxPlcExternalConnectionDataEx>();
        Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx> dictionary1 = new Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx>();
        foreach (ITxPlcExternalConnectionDataEx importedData in xlImportParams.ImportedDataList)
        {
          int dataIndexByFilter = this.FindIdenticalDataIndexByFilter(importedData, CApECExternalConnectionsManager.eConnectionDataFilterFlags.Name, list, 0);
          if (dataIndexByFilter >= 0)
          {
            TxPlcExternalConnectionEx key = connections[dataIndexByFilter];
            if (dictionary1.ContainsKey(key))
              dictionary1[key] = importedData;
            else
              dictionary1.Add(key, importedData);
          }
          else
            connectionDataExList.Add(importedData);
        }
        Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx> dictionary2 = new Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx>();
        Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx>.Enumerator enumerator1 = dictionary1.GetEnumerator();
        bool applyToRest = false;
        bool flag2 = false;
        while (enumerator1.MoveNext())
        {
          KeyValuePair<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx> current;
          if (!applyToRest)
          {
            current = enumerator1.Current;
            switch (this.AskUserModifyOnImport(current.Key.Data.Name, out applyToRest))
            {
              case DialogResult.Yes:
                flag2 = true;
                break;
              case DialogResult.No:
                flag2 = false;
                break;
              default:
                dictionary2.Clear();
                goto label_28;
            }
          }
          if (flag2)
          {
            Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx> dictionary3 = dictionary2;
            current = enumerator1.Current;
            TxPlcExternalConnectionEx key = current.Key;
            current = enumerator1.Current;
            ITxPlcExternalConnectionDataEx connectionDataEx = current.Value;
            dictionary3.Add(key, connectionDataEx);
          }
        }
label_28:
        if (connectionDataExList.Count > 0 || dictionary2.Count > 0)
        {
          List<CApECExternalConnectionNode> importedNodes = new List<CApECExternalConnectionNode>(connectionDataExList.Count);
          List<CApECExternalConnectionNode> modifiedNodes = new List<CApECExternalConnectionNode>(dictionary2.Count);
          List<string> stringList1 = new List<string>();
          List<string> stringList2 = new List<string>();
          ((ScrollableControl) this.m_grid).BeginUpdate();
          try
          {
            foreach (ITxPlcExternalConnectionDataEx creationData in connectionDataExList)
            {
              CApECExternalConnectionsManager.eCreateConnectionFailiureReason failiureReason;
              CApECExternalConnectionNode connection = this.CreateConnection(creationData, out failiureReason);
              if (connection != null)
              {
                importedNodes.Add(connection);
              }
              else
              {
                string str1 = $"'{creationData.Name}': ";
                string str2;
                if (failiureReason == CApECExternalConnectionsManager.eCreateConnectionFailiureReason.DuplicatedKey)
                {
                  switch (creationData)
                  {
                    case TxPlcSimitCouplingConnectionDataEx _:
                      TxPlcSimitCouplingConnectionDataEx connectionDataEx1 = creationData as TxPlcSimitCouplingConnectionDataEx;
                      str2 = str1 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_SIMIT_DUPLICATED_KEY, (object) connectionDataEx1.COMElement);
                      break;
                    case TxPlcSimAdvConnectionDataEx _:
                      TxPlcSimAdvConnectionDataEx connectionDataEx2 = creationData as TxPlcSimAdvConnectionDataEx;
                      str2 = !connectionDataEx2.LocalConnection ? str1 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_PLCSIM_ADV_REMOTE_DUPLICATED_KEY, (object) connectionDataEx2.EndpointUrl, (object) connectionDataEx2.EndpointName, (object) connectionDataEx2.Port) : str1 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_PLCSIM_ADV_LOCAL_DUPLICATED_KEY, (object) connectionDataEx2.EndpointName);
                      break;
                    case TxPlcWinModConnectionDataEx _:
                      TxPlcWinModConnectionDataEx connectionDataEx3 = creationData as TxPlcWinModConnectionDataEx;
                      str2 = str1 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_WINMOD_DUPLICATED_KEY, (object) connectionDataEx3.EndpointUrl, (object) connectionDataEx3.EndpointName, (object) connectionDataEx3.Port);
                      break;
                    case TxPlcUserDefinedConnectionDataEx _:
                      TxPlcUserDefinedConnectionDataEx connectionDataEx4 = creationData as TxPlcUserDefinedConnectionDataEx;
                      str2 = str1 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_USER_DEFINED_DUPLICATED_KEY, (object) connectionDataEx4.EndpointUrl, (object) connectionDataEx4.EndpointName, (object) connectionDataEx4.Port);
                      break;
                    default:
                      str2 = str1 + CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_UNKNOWN_REASON;
                      break;
                  }
                }
                else
                  str2 = str1 + CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_UNKNOWN_REASON;
                stringList1.Add(str2);
              }
            }
            Dictionary<TxPlcExternalConnectionEx, ITxPlcExternalConnectionDataEx>.Enumerator enumerator2 = dictionary2.GetEnumerator();
            while (enumerator2.MoveNext())
            {
              TxPlcExternalConnectionEx key = enumerator2.Current.Key;
              ITxPlcExternalConnectionDataEx data = enumerator2.Current.Value;
              CApECExternalConnectionsManager.eSetConnectionDataFailiureReason failiureReason;
              if (this.SetConnectionData(key, data, out failiureReason))
              {
                modifiedNodes.Add(this.CreateConnectionNode(key));
              }
              else
              {
                string str3 = $"'{data.Name}': ";
                string str4;
                if (failiureReason == CApECExternalConnectionsManager.eSetConnectionDataFailiureReason.DuplicatedKey)
                {
                  switch (data)
                  {
                    case TxPlcSimitCouplingConnectionDataEx _:
                      TxPlcSimitCouplingConnectionDataEx connectionDataEx5 = data as TxPlcSimitCouplingConnectionDataEx;
                      str4 = str3 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_SIMIT_DUPLICATED_KEY, (object) connectionDataEx5.COMElement);
                      break;
                    case TxPlcSimAdvConnectionDataEx _:
                      TxPlcSimAdvConnectionDataEx connectionDataEx6 = data as TxPlcSimAdvConnectionDataEx;
                      str4 = !connectionDataEx6.LocalConnection ? str3 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_PLCSIM_ADV_REMOTE_DUPLICATED_KEY, (object) connectionDataEx6.EndpointUrl, (object) connectionDataEx6.EndpointName, (object) connectionDataEx6.Port) : str3 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_PLCSIM_ADV_LOCAL_DUPLICATED_KEY, (object) connectionDataEx6.EndpointName);
                      break;
                    case TxPlcWinModConnectionDataEx _:
                      TxPlcWinModConnectionDataEx connectionDataEx7 = data as TxPlcWinModConnectionDataEx;
                      str4 = str3 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_WINMOD_DUPLICATED_KEY, (object) connectionDataEx7.EndpointUrl, (object) connectionDataEx7.EndpointName, (object) connectionDataEx7.Port);
                      break;
                    case TxPlcUserDefinedConnectionDataEx _:
                      TxPlcUserDefinedConnectionDataEx connectionDataEx8 = data as TxPlcUserDefinedConnectionDataEx;
                      str4 = str3 + string.Format(CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_USER_DEFINED_DUPLICATED_KEY, (object) connectionDataEx8.EndpointUrl, (object) connectionDataEx8.EndpointName, (object) connectionDataEx8.Port);
                      break;
                    default:
                      str4 = str3 + CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_UNKNOWN_REASON;
                      break;
                  }
                }
                else
                  str4 = str3 + CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_UNKNOWN_REASON;
                stringList2.Add(str4);
              }
            }
            outputParams = new CApECExternalConnectionsManager.ImportOutputParams(xlImportParams, importedNodes, modifiedNodes);
          }
          finally
          {
            ((ScrollableControl) this.m_grid).EndUpdate();
            if (stringList1.Count > 0 || stringList2.Count > 0)
            {
              string str5 = string.Empty;
              if (stringList1.Count > 0)
              {
                str5 += CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_FAILED_TO_CREATE_CONNECTIONS;
                foreach (string str6 in stringList1)
                  str5 = str5 + Environment.NewLine + Environment.NewLine + str6;
              }
              if (stringList2.Count > 0)
              {
                if (str5 != string.Empty)
                  str5 = str5 + Environment.NewLine + Environment.NewLine;
                str5 += CUiECExternalConnectionsResourceTable.IMPORT_ERR_MSG_FAILED_TO_MODIFY_CONNECTIONS;
                foreach (string str7 in stringList2)
                  str5 = str5 + Environment.NewLine + Environment.NewLine + str7;
              }
              int num = (int) TxMessageBox.ShowModal(str5, CUiECExternalConnectionsResourceTable.IMPORT_FROM_EXCEL_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
          }
        }
      }
    }
    return flag1;
  }

  private int FindIdenticalDataIndexByFilter(
    ITxPlcExternalConnectionDataEx data,
    CApECExternalConnectionsManager.eConnectionDataFilterFlags filterFlags,
    List<ITxPlcExternalConnectionDataEx> list,
    int startIndex)
  {
    int dataIndexByFilter = -1;
    for (int index = startIndex; index < list.Count; ++index)
    {
      ITxPlcExternalConnectionDataEx connectionDataEx1 = list[index];
      bool flag = false;
      if ((filterFlags & CApECExternalConnectionsManager.eConnectionDataFilterFlags.All) == CApECExternalConnectionsManager.eConnectionDataFilterFlags.All)
      {
        if (data.ConnectionType == connectionDataEx1.ConnectionType)
        {
          if (connectionDataEx1.ConnectionType == null)
          {
            TxPlcOpcConnectionDataEx connectionDataEx2 = data as TxPlcOpcConnectionDataEx;
            TxPlcOpcConnectionDataEx connectionDataEx3 = connectionDataEx1 as TxPlcOpcConnectionDataEx;
            flag = connectionDataEx2.Name == connectionDataEx1.Name && connectionDataEx2.ConnectionType == connectionDataEx3.ConnectionType && connectionDataEx2.IsRemoteServer == connectionDataEx3.IsRemoteServer && connectionDataEx2.ServerId == connectionDataEx3.ServerId && connectionDataEx2.ServerPath == connectionDataEx3.ServerPath && connectionDataEx2.ItemHeader == connectionDataEx3.ItemHeader && connectionDataEx2.MapSignalsType == connectionDataEx3.MapSignalsType;
          }
          if (connectionDataEx1.ConnectionType == 2)
          {
            TxPlcOpcUAConnectionDataEx connectionDataEx4 = data as TxPlcOpcUAConnectionDataEx;
            TxPlcOpcUAConnectionDataEx connectionDataEx5 = connectionDataEx1 as TxPlcOpcUAConnectionDataEx;
            flag = connectionDataEx4.Name == connectionDataEx1.Name && connectionDataEx4.ConnectionType == connectionDataEx5.ConnectionType && connectionDataEx4.EndPointUrl == connectionDataEx5.EndPointUrl && connectionDataEx4.DiscoveryPort == connectionDataEx5.DiscoveryPort && connectionDataEx4.EndPointName == connectionDataEx5.EndPointName && connectionDataEx4.ItemHeader == connectionDataEx5.ItemHeader && connectionDataEx4.MapSignalsType == connectionDataEx5.MapSignalsType;
          }
          else if (data.ConnectionType == 1)
          {
            TxPlcSimbaConnectionDataEx connectionDataEx6 = data as TxPlcSimbaConnectionDataEx;
            TxPlcSimbaConnectionDataEx connectionDataEx7 = connectionDataEx1 as TxPlcSimbaConnectionDataEx;
            flag = connectionDataEx6.Name == connectionDataEx7.Name && connectionDataEx6.ConnectionType == connectionDataEx7.ConnectionType && connectionDataEx6.HardwareIndex == connectionDataEx7.HardwareIndex && connectionDataEx6.MapSignalsType == connectionDataEx7.MapSignalsType;
          }
          else if (data.ConnectionType == 3)
          {
            TxPlcSimAdvConnectionDataEx connectionDataEx8 = data as TxPlcSimAdvConnectionDataEx;
            TxPlcSimAdvConnectionDataEx connectionDataEx9 = connectionDataEx1 as TxPlcSimAdvConnectionDataEx;
            flag = connectionDataEx8.Name == connectionDataEx9.Name || connectionDataEx8.LocalConnection == connectionDataEx9.LocalConnection && connectionDataEx8.EndpointName == connectionDataEx9.EndpointName && connectionDataEx8.EndpointUrl == connectionDataEx9.EndpointUrl && connectionDataEx8.Port == connectionDataEx9.Port;
          }
          else if (data.ConnectionType == 4)
          {
            TxPlcWinModConnectionDataEx connectionDataEx10 = data as TxPlcWinModConnectionDataEx;
            TxPlcWinModConnectionDataEx connectionDataEx11 = connectionDataEx1 as TxPlcWinModConnectionDataEx;
            flag = connectionDataEx10.Name == connectionDataEx11.Name || connectionDataEx10.EndpointName == connectionDataEx11.EndpointName && connectionDataEx10.EndpointUrl == connectionDataEx11.EndpointUrl && connectionDataEx10.COMElement == connectionDataEx11.COMElement && connectionDataEx10.Port == connectionDataEx11.Port;
          }
          else if (data.ConnectionType == 6)
          {
            TxPlcUserDefinedConnectionDataEx connectionDataEx12 = data as TxPlcUserDefinedConnectionDataEx;
            TxPlcUserDefinedConnectionDataEx connectionDataEx13 = connectionDataEx1 as TxPlcUserDefinedConnectionDataEx;
            flag = connectionDataEx12.Name == connectionDataEx13.Name || connectionDataEx12.EndpointName == connectionDataEx13.EndpointName && connectionDataEx12.EndpointUrl == connectionDataEx13.EndpointUrl && connectionDataEx12.COMElement == connectionDataEx13.COMElement && connectionDataEx12.Port == connectionDataEx13.Port;
          }
          else if (data.ConnectionType == 5)
          {
            TxPlcSimitCouplingConnectionDataEx connectionDataEx14 = data as TxPlcSimitCouplingConnectionDataEx;
            TxPlcSimitCouplingConnectionDataEx connectionDataEx15 = connectionDataEx1 as TxPlcSimitCouplingConnectionDataEx;
            flag = connectionDataEx14.Name == connectionDataEx15.Name && connectionDataEx14.EndpointName == connectionDataEx15.EndpointName && connectionDataEx14.EndpointUrl == connectionDataEx15.EndpointUrl && connectionDataEx14.COMElement == connectionDataEx15.COMElement;
          }
        }
      }
      else
      {
        flag = true;
        if ((filterFlags & CApECExternalConnectionsManager.eConnectionDataFilterFlags.Name) == CApECExternalConnectionsManager.eConnectionDataFilterFlags.Name)
          flag = data.Name == connectionDataEx1.Name;
        if (flag && (filterFlags & CApECExternalConnectionsManager.eConnectionDataFilterFlags.Server) == CApECExternalConnectionsManager.eConnectionDataFilterFlags.Server && data.ConnectionType == connectionDataEx1.ConnectionType && connectionDataEx1.ConnectionType == null)
        {
          TxPlcOpcConnectionDataEx connectionDataEx16 = data as TxPlcOpcConnectionDataEx;
          TxPlcOpcConnectionDataEx connectionDataEx17 = connectionDataEx1 as TxPlcOpcConnectionDataEx;
          flag = connectionDataEx16.IsRemoteServer == connectionDataEx17.IsRemoteServer && connectionDataEx16.ServerId == connectionDataEx17.ServerId && connectionDataEx16.ServerPath == connectionDataEx17.ServerPath;
        }
        if (flag && (filterFlags & CApECExternalConnectionsManager.eConnectionDataFilterFlags.ItemHeader) == CApECExternalConnectionsManager.eConnectionDataFilterFlags.ItemHeader && data.ConnectionType == connectionDataEx1.ConnectionType && connectionDataEx1.ConnectionType == null)
          flag = (data as TxPlcOpcConnectionDataEx).ItemHeader == (connectionDataEx1 as TxPlcOpcConnectionDataEx).ItemHeader;
        if (flag && (filterFlags & CApECExternalConnectionsManager.eConnectionDataFilterFlags.MapSignalsBy) == CApECExternalConnectionsManager.eConnectionDataFilterFlags.MapSignalsBy && data.ConnectionType == connectionDataEx1.ConnectionType)
          flag = data.MapSignalsType == connectionDataEx1.MapSignalsType;
      }
      if (flag)
      {
        dataIndexByFilter = index;
        break;
      }
    }
    return dataIndexByFilter;
  }

  private DialogResult AskUserModifyOnImport(string connectionName, out bool applyToRest)
  {
    applyToRest = false;
    string fromExcelCaption = CUiECExternalConnectionsResourceTable.IMPORT_FROM_EXCEL_CAPTION;
    return TxMessageBox.ShowModal(string.Format(CUiECExternalConnectionsResourceTable.WARNING_MODIFY_EXISTING_CONNECTION, (object) connectionName), fromExcelCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
  }

  private void UpdatePlcSimAdvancedFilter(TxPlcExternalConnectionEx connection)
  {
    if (!(connection.Data is TxPlcSimAdvConnectionDataEx))
      return;
    TxPlcSimAdvConnectionDataEx data = connection.Data as TxPlcSimAdvConnectionDataEx;
    string key = this.m_plcimAdvancedConnctionMap.FirstOrDefault<KeyValuePair<string, string>>((Func<KeyValuePair<string, string>, bool>) (x => x.Value == connection.Id)).Key;
    switch (key)
    {
      case null:
        break;
      case "":
        break;
      default:
        this.m_plcimAdvancedConnctionMap.Remove(key);
        this.m_plcimAdvancedConnctionMap[this.formatPlcismAdvancedKey(data)] = connection.Id;
        break;
    }
  }

  private void UpdateWinModFilter(TxPlcExternalConnectionEx connection)
  {
    if (!(connection.Data is TxPlcWinModConnectionDataEx))
      return;
    TxPlcWinModConnectionDataEx data = connection.Data as TxPlcWinModConnectionDataEx;
    string key = this.m_winModConnctionMap.FirstOrDefault<KeyValuePair<string, string>>((Func<KeyValuePair<string, string>, bool>) (x => x.Value == connection.Id)).Key;
    switch (key)
    {
      case null:
        break;
      case "":
        break;
      default:
        this.m_winModConnctionMap.Remove(key);
        this.m_winModConnctionMap[this.formatWinModKey(data)] = connection.Id;
        break;
    }
  }

  private void UpdateSimitCouplingFilter(TxPlcExternalConnectionEx connection)
  {
    if (!(connection.Data is TxPlcSimitCouplingConnectionDataEx))
      return;
    TxPlcSimitCouplingConnectionDataEx data = connection.Data as TxPlcSimitCouplingConnectionDataEx;
    string key = this.m_simitCouplingConnectionMap.FirstOrDefault<KeyValuePair<string, string>>((Func<KeyValuePair<string, string>, bool>) (x => x.Value == connection.Id)).Key;
    if (string.IsNullOrEmpty(key))
      return;
    this.m_simitCouplingConnectionMap.Remove(key);
    this.m_simitCouplingConnectionMap[this.formatSimitCouplingKey(data)] = connection.Id;
  }

  private void UpdateUserDefinedFilter(TxPlcExternalConnectionEx connection)
  {
    if (!(connection.Data is TxPlcUserDefinedConnectionDataEx))
      return;
    TxPlcUserDefinedConnectionDataEx data = connection.Data as TxPlcUserDefinedConnectionDataEx;
    string key = this.m_userDefinedConnectionMap.FirstOrDefault<KeyValuePair<string, string>>((Func<KeyValuePair<string, string>, bool>) (x => x.Value == connection.Id)).Key;
    if (string.IsNullOrEmpty(key))
      return;
    this.m_userDefinedConnectionMap.Remove(key);
    this.m_userDefinedConnectionMap[this.formatUserDefinedKey(data)] = connection.Id;
  }

  internal static string GetServerPortFromData(ITxPlcExternalConnectionDataEx data)
  {
    string discoveryPortNoValue;
    switch (data)
    {
      case TxPlcOpcUAConnectionDataEx _:
        discoveryPortNoValue = Convert.ToString((data as TxPlcOpcUAConnectionDataEx).DiscoveryPort);
        break;
      case TxPlcSimAdvConnectionDataEx _:
        discoveryPortNoValue = Convert.ToString((data as TxPlcSimAdvConnectionDataEx).Port);
        break;
      case TxPlcWinModConnectionDataEx _:
        discoveryPortNoValue = Convert.ToString((data as TxPlcWinModConnectionDataEx).Port);
        break;
      default:
        discoveryPortNoValue = CUiECExternalConnectionsResourceTable.DISCOVERY_PORT_NO_VALUE;
        break;
    }
    return discoveryPortNoValue;
  }

  internal static void SetServerPortToData(string portString, ITxPlcExternalConnectionDataEx data)
  {
    switch (data)
    {
      case TxPlcOpcUAConnectionDataEx _:
        TxPlcOpcUAConnectionDataEx connectionDataEx1 = data as TxPlcOpcUAConnectionDataEx;
        if (portString == null)
          break;
        int int32_1 = Convert.ToInt32(portString);
        connectionDataEx1.DiscoveryPort = int32_1;
        break;
      case TxPlcSimAdvConnectionDataEx _:
        TxPlcSimAdvConnectionDataEx connectionDataEx2 = data as TxPlcSimAdvConnectionDataEx;
        if (portString != null && portString != "")
        {
          int int32_2 = Convert.ToInt32(portString);
          connectionDataEx2.Port = int32_2;
          break;
        }
        connectionDataEx2.Port = 0;
        break;
      case TxPlcWinModConnectionDataEx _:
        TxPlcWinModConnectionDataEx connectionDataEx3 = data as TxPlcWinModConnectionDataEx;
        if (portString != null && portString != "")
        {
          int int32_3 = Convert.ToInt32(portString);
          connectionDataEx3.Port = int32_3;
          break;
        }
        connectionDataEx3.Port = 0;
        break;
      default:
        if (portString.Equals(CUiECExternalConnectionsResourceTable.DISCOVERY_PORT_NO_VALUE, StringComparison.InvariantCultureIgnoreCase))
          break;
        throw new ArgumentException();
    }
  }

  internal static string GetNameSpaceIndexFromData(ITxPlcExternalConnectionDataEx data)
  {
    return !(data is TxPlcOpcUAConnectionDataEx) ? CUiECExternalConnectionsResourceTable.NAME_SPACE_INDEX_NO_VALUE : Convert.ToString((data as TxPlcOpcUAConnectionDataEx).NameSpaceIndex);
  }

  internal static void SetNameSpaceIndexToData(
    string nameSpaceIndexString,
    ITxPlcExternalConnectionDataEx data)
  {
    bool flag = true;
    if (data is TxPlcOpcUAConnectionDataEx)
    {
      TxPlcOpcUAConnectionDataEx connectionDataEx = data as TxPlcOpcUAConnectionDataEx;
      int result = 0;
      if (nameSpaceIndexString != null && int.TryParse(nameSpaceIndexString, out result))
        connectionDataEx.NameSpaceIndex = result;
      else
        flag = false;
    }
    else if (!nameSpaceIndexString.Equals(CUiECExternalConnectionsResourceTable.NAME_SPACE_INDEX_NO_VALUE, StringComparison.InvariantCultureIgnoreCase))
      flag = false;
    if (!flag)
      throw new ArgumentException();
  }

  internal static string GetEndPointUrlFromData(ITxPlcExternalConnectionDataEx data)
  {
    string str = "";
    return data is TxPlcOpcUAConnectionDataEx ? (data as TxPlcOpcUAConnectionDataEx).EndPointUrl : str;
  }

  internal static string GetPluginStateFromData(ITxPlcExternalConnectionDataEx data)
  {
    string str = "N\\A";
    return data is TxPlcUserDefinedConnectionDataEx ? (data as TxPlcUserDefinedConnectionDataEx).EndpointUrl : str;
  }

  internal static void SetPluginStateToData(
    string endPointUrlString,
    ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcUserDefinedConnectionDataEx))
      return;
    TxPlcUserDefinedConnectionDataEx connectionDataEx = data as TxPlcUserDefinedConnectionDataEx;
    if (endPointUrlString == null)
      return;
    connectionDataEx.EndpointUrl = endPointUrlString;
  }

  internal static void SetEndPointUrlToData(
    string endPointUrlString,
    ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcOpcUAConnectionDataEx))
      return;
    TxPlcOpcUAConnectionDataEx connectionDataEx = data as TxPlcOpcUAConnectionDataEx;
    if (endPointUrlString == null)
      return;
    connectionDataEx.EndPointUrl = endPointUrlString;
  }

  internal static string GetEndPointNameFromData(ITxPlcExternalConnectionDataEx data)
  {
    string str = "";
    return data is TxPlcOpcUAConnectionDataEx ? (data as TxPlcOpcUAConnectionDataEx).EndPointName : str;
  }

  internal static void SetEndPointNameToData(
    string endPointNameString,
    ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcOpcUAConnectionDataEx))
      return;
    TxPlcOpcUAConnectionDataEx connectionDataEx = data as TxPlcOpcUAConnectionDataEx;
    if (endPointNameString == null)
      return;
    connectionDataEx.EndPointName = endPointNameString;
  }

  internal static string GetServerFromData(ITxPlcExternalConnectionDataEx data)
  {
    string format = "";
    switch (data)
    {
      case TxPlcOpcConnectionDataEx _:
        TxPlcOpcConnectionDataEx connectionDataEx1 = data as TxPlcOpcConnectionDataEx;
        return $"{(connectionDataEx1.IsRemoteServer ? (object) connectionDataEx1.ServerPath : (object) "local")}\\{connectionDataEx1.ServerId}";
      case TxPlcSimAdvConnectionDataEx _:
        TxPlcSimAdvConnectionDataEx connectionDataEx2 = data as TxPlcSimAdvConnectionDataEx;
        return string.Format(!(connectionDataEx2.EndpointUrl != "") ? "local" : connectionDataEx2.EndpointUrl);
      case TxPlcWinModConnectionDataEx _:
        TxPlcWinModConnectionDataEx connectionDataEx3 = data as TxPlcWinModConnectionDataEx;
        if (connectionDataEx3.EndpointUrl != "")
          format = connectionDataEx3.EndpointUrl;
        return string.Format(format);
      case TxPlcUserDefinedConnectionDataEx _:
        TxPlcUserDefinedConnectionDataEx connectionDataEx4 = data as TxPlcUserDefinedConnectionDataEx;
        return string.Format("local");
      case TxPlcOpcUAConnectionDataEx _:
        return (data as TxPlcOpcUAConnectionDataEx).EndPointDescription;
      case TxPlcSimbaConnectionDataEx _:
        return CUiECExternalConnectionsResourceTable.SERVER_VALUE_FOR_SIMBA;
      case TxPlcSimitCouplingConnectionDataEx _:
        TxPlcSimitCouplingConnectionDataEx connectionDataEx5 = data as TxPlcSimitCouplingConnectionDataEx;
        return connectionDataEx5.EndpointUrl.Length <= 0 ? "localhost" : connectionDataEx5.EndpointUrl;
      default:
        return format;
    }
  }

  internal static void SetServerToData(string serverString, ITxPlcExternalConnectionDataEx data)
  {
    switch (data)
    {
      case TxPlcOpcConnectionDataEx _:
        TxPlcOpcConnectionDataEx connectionDataEx1 = data as TxPlcOpcConnectionDataEx;
        string str1 = string.Empty;
        string empty = string.Empty;
        int length = serverString.LastIndexOf('\\');
        string str2;
        if (length >= 0)
        {
          str2 = serverString.Substring(length + 1);
          str1 = serverString.Substring(0, length);
        }
        else
          str2 = serverString;
        if (str1.Length > 0 && !str1.EndsWith("local", StringComparison.InvariantCultureIgnoreCase))
        {
          connectionDataEx1.IsRemoteServer = true;
          connectionDataEx1.ServerPath = str1;
        }
        else
        {
          connectionDataEx1.IsRemoteServer = false;
          connectionDataEx1.ServerPath = string.Empty;
        }
        connectionDataEx1.ServerId = str2;
        break;
      case TxPlcOpcUAConnectionDataEx _:
        TxPlcOpcUAConnectionDataEx connectionDataEx2 = data as TxPlcOpcUAConnectionDataEx;
        if (serverString == null)
          break;
        connectionDataEx2.EndPointDescription = serverString;
        connectionDataEx2.EndPointUrl = serverString;
        break;
      case TxPlcSimbaConnectionDataEx _:
        if (serverString.Equals(CUiECExternalConnectionsResourceTable.SERVER_VALUE_FOR_SIMBA, StringComparison.InvariantCultureIgnoreCase))
          break;
        throw new ArgumentException();
      case TxPlcSimAdvConnectionDataEx _:
        TxPlcSimAdvConnectionDataEx connectionDataEx3 = data as TxPlcSimAdvConnectionDataEx;
        if (serverString == null)
          break;
        connectionDataEx3.EndpointUrl = serverString;
        break;
      case TxPlcWinModConnectionDataEx _:
        TxPlcWinModConnectionDataEx connectionDataEx4 = data as TxPlcWinModConnectionDataEx;
        if (serverString == null)
          break;
        connectionDataEx4.EndpointUrl = serverString;
        break;
      case TxPlcUserDefinedConnectionDataEx _:
        TxPlcUserDefinedConnectionDataEx connectionDataEx5 = data as TxPlcUserDefinedConnectionDataEx;
        if (serverString == null)
          break;
        connectionDataEx5.EndpointUrl = serverString;
        break;
      case TxPlcSimitCouplingConnectionDataEx _:
        TxPlcSimitCouplingConnectionDataEx connectionDataEx6 = data as TxPlcSimitCouplingConnectionDataEx;
        if (serverString == null)
          break;
        connectionDataEx6.EndpointUrl = serverString;
        break;
    }
  }

  internal static string GetItemHeaderFromData(ITxPlcExternalConnectionDataEx data)
  {
    string itemHeaderFromData = (string) null;
    switch (data)
    {
      case TxPlcOpcConnectionDataEx _:
        itemHeaderFromData = (data as TxPlcOpcConnectionDataEx).ItemHeader;
        break;
      case TxPlcOpcUAConnectionDataEx _:
        itemHeaderFromData = (data as TxPlcOpcUAConnectionDataEx).ItemHeader;
        break;
      case TxPlcSimbaConnectionDataEx _:
        int hardwareIndex = (data as TxPlcSimbaConnectionDataEx).HardwareIndex;
        string str = "S0";
        if (hardwareIndex - 10 < 0)
          str += "0";
        itemHeaderFromData = str + hardwareIndex.ToString();
        break;
      case TxPlcSimAdvConnectionDataEx _:
        itemHeaderFromData = CUiECExternalConnectionsResourceTable.ITEM_HEADER_VALUE_FOR_OPC_UA;
        break;
      case TxPlcWinModConnectionDataEx _:
        itemHeaderFromData = (data as TxPlcWinModConnectionDataEx).ItemHeader;
        break;
      case TxPlcSimitCouplingConnectionDataEx _:
        itemHeaderFromData = (data as TxPlcSimitCouplingConnectionDataEx).ItemHeader;
        break;
      case TxPlcUserDefinedConnectionDataEx _:
        itemHeaderFromData = "N\\A";
        break;
    }
    return itemHeaderFromData;
  }

  internal static void SetItemHeaderFromData(
    string itemHeaderString,
    ITxPlcExternalConnectionDataEx data)
  {
    switch (data)
    {
      case TxPlcOpcConnectionDataEx _:
        (data as TxPlcOpcConnectionDataEx).ItemHeader = itemHeaderString.Trim();
        break;
      case TxPlcSimbaConnectionDataEx _:
        try
        {
          int int32 = Convert.ToInt32(itemHeaderString.Trim().Substring(2));
          (data as TxPlcSimbaConnectionDataEx).HardwareIndex = int32;
          break;
        }
        catch (Exception ex)
        {
          throw new ArgumentException();
        }
      case TxPlcOpcUAConnectionDataEx _:
        (data as TxPlcOpcUAConnectionDataEx).ItemHeader = itemHeaderString.Trim();
        break;
      case TxPlcWinModConnectionDataEx _:
        (data as TxPlcWinModConnectionDataEx).ItemHeader = itemHeaderString.Trim();
        break;
      case TxPlcSimitCouplingConnectionDataEx _:
        (data as TxPlcSimitCouplingConnectionDataEx).ItemHeader = itemHeaderString.Trim();
        break;
      case TxPlcUserDefinedConnectionDataEx _:
        (data as TxPlcUserDefinedConnectionDataEx).ItemHeader = "N\\A";
        break;
    }
  }

  internal static string GetMapSignalsTypeFromData(
    ITxPlcExternalConnectionDataEx data,
    CApECExternalConnectionsManager.eConnectionDataFormat format)
  {
    string signalsTypeFromData = string.Empty;
    TxPlcExternalMapSignalsTypeEx mapSignalsType = data.MapSignalsType;
    if (mapSignalsType != null)
    {
      if (mapSignalsType == 1)
      {
        switch (format)
        {
          case CApECExternalConnectionsManager.eConnectionDataFormat.Grid:
            signalsTypeFromData = CUiECExternalConnectionsResourceTable.MAP_BY_SERVER_ADDRESS;
            break;
          case CApECExternalConnectionsManager.eConnectionDataFormat.Export:
            signalsTypeFromData = "Server address";
            break;
          case CApECExternalConnectionsManager.eConnectionDataFormat.Edit:
            signalsTypeFromData = CUiECExternalConnectionsResourceTable.EDIT_DLG_MAP_BY_SERVER_ADDRESS;
            break;
        }
      }
    }
    else
    {
      switch (format)
      {
        case CApECExternalConnectionsManager.eConnectionDataFormat.Grid:
          signalsTypeFromData = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
          break;
        case CApECExternalConnectionsManager.eConnectionDataFormat.Export:
          signalsTypeFromData = "Signal name";
          break;
        case CApECExternalConnectionsManager.eConnectionDataFormat.Edit:
          signalsTypeFromData = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
          break;
      }
    }
    return signalsTypeFromData;
  }

  internal static void SetMapSignalsTypeToData(
    string mapSignalsTypeString,
    CApECExternalConnectionsManager.eConnectionDataFormat format,
    ITxPlcExternalConnectionDataEx data)
  {
    bool flag = true;
    string str1 = (string) null;
    string str2 = (string) null;
    switch (format)
    {
      case CApECExternalConnectionsManager.eConnectionDataFormat.Grid:
        str1 = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
        str2 = CUiECExternalConnectionsResourceTable.MAP_BY_SERVER_ADDRESS;
        break;
      case CApECExternalConnectionsManager.eConnectionDataFormat.Export:
        str1 = "Signal name";
        str2 = "Server address";
        break;
      case CApECExternalConnectionsManager.eConnectionDataFormat.Edit:
        str1 = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
        str2 = CUiECExternalConnectionsResourceTable.EDIT_DLG_MAP_BY_SERVER_ADDRESS;
        break;
      default:
        flag = false;
        break;
    }
    if (flag)
    {
      if (mapSignalsTypeString.Equals(str1, StringComparison.InvariantCultureIgnoreCase))
        data.MapSignalsType = (TxPlcExternalMapSignalsTypeEx) 0;
      else if (mapSignalsTypeString.Equals(str2, StringComparison.InvariantCultureIgnoreCase))
        data.MapSignalsType = (TxPlcExternalMapSignalsTypeEx) 1;
      else
        flag = false;
    }
    if (!flag)
      throw new ArgumentException();
  }

  internal static string[] GetMapSignalsTypeOptions(
    CApECExternalConnectionsManager.eConnectionDataFormat format)
  {
    string[] signalsTypeOptions = new string[2];
    switch (format)
    {
      case CApECExternalConnectionsManager.eConnectionDataFormat.Grid:
        signalsTypeOptions[0] = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
        signalsTypeOptions[1] = CUiECExternalConnectionsResourceTable.MAP_BY_SERVER_ADDRESS;
        break;
      case CApECExternalConnectionsManager.eConnectionDataFormat.Export:
        signalsTypeOptions[0] = "Signal name";
        signalsTypeOptions[1] = "Server address";
        break;
      case CApECExternalConnectionsManager.eConnectionDataFormat.Edit:
        signalsTypeOptions[0] = CUiECExternalConnectionsResourceTable.MAP_BY_SIGNAL_NAME;
        signalsTypeOptions[1] = CUiECExternalConnectionsResourceTable.EDIT_DLG_MAP_BY_SERVER_ADDRESS;
        break;
    }
    return signalsTypeOptions;
  }

  internal static string GetConnectionTypeFromData(ITxPlcExternalConnectionDataEx data)
  {
    string connectionTypeFromData = string.Empty;
    switch (data)
    {
      case TxPlcOpcConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.OPC_DA_TYPE;
        break;
      case TxPlcOpcUAConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.OPC_UA_TYPE;
        break;
      case TxPlcSimbaConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.SIMBA_PNIO_TYPE;
        break;
      case TxPlcSimAdvConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.PLCSIM_ADVANCED_TYPE;
        break;
      case TxPlcWinModConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.WIN_MODE_TYPE;
        break;
      case TxPlcSimitCouplingConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.SIMIT_COUPLING_TYPE;
        break;
      case TxPlcUserDefinedConnectionDataEx _:
        connectionTypeFromData = CUiECExternalConnectionsResourceTable.USER_DEFINED_TYPE;
        break;
    }
    return connectionTypeFromData;
  }

  internal static void SetLocalPLCSIMAdvancedToData(bool local, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      throw new ArgumentException();
    (data as TxPlcSimAdvConnectionDataEx).LocalConnection = local;
  }

  internal static bool GetLocalPLCSIMAdvancedFromData(ITxPlcExternalConnectionDataEx data)
  {
    bool advancedFromData = true;
    if (data is TxPlcSimAdvConnectionDataEx)
      advancedFromData = (data as TxPlcSimAdvConnectionDataEx).LocalConnection;
    return advancedFromData;
  }

  internal static void SetInstanceNameToData(
    string instanceNameString,
    ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return;
    TxPlcSimAdvConnectionDataEx connectionDataEx = data as TxPlcSimAdvConnectionDataEx;
    if (instanceNameString == null)
      return;
    connectionDataEx.EndpointName = instanceNameString.Trim();
  }

  internal static string GetInstanceNameFromData(ITxPlcExternalConnectionDataEx data)
  {
    string str = "";
    return data is TxPlcSimAdvConnectionDataEx ? (data as TxPlcSimAdvConnectionDataEx).EndpointName : (str = CUiECExternalConnectionsResourceTable.NO_VALUE);
  }

  internal static void SetInstanceTimeoutToData(int timeout, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return;
    (data as TxPlcSimAdvConnectionDataEx).InstanceTimeout = timeout;
  }

  internal static string GetCOMElementFromData(ITxPlcExternalConnectionDataEx data)
  {
    string str = "";
    switch (data)
    {
      case TxPlcWinModConnectionDataEx _:
        return (data as TxPlcWinModConnectionDataEx).EndpointName;
      case TxPlcSimitCouplingConnectionDataEx _:
        return (data as TxPlcSimitCouplingConnectionDataEx).EndpointName;
      case TxPlcUserDefinedConnectionDataEx _:
        return (data as TxPlcUserDefinedConnectionDataEx).COMElement;
      default:
        return str = CUiECExternalConnectionsResourceTable.NO_VALUE;
    }
  }

  internal static void SetCOMElementToData(
    string comElementString,
    ITxPlcExternalConnectionDataEx data)
  {
    switch (data)
    {
      case TxPlcWinModConnectionDataEx _:
        TxPlcWinModConnectionDataEx connectionDataEx1 = data as TxPlcWinModConnectionDataEx;
        if (comElementString == null)
          break;
        connectionDataEx1.EndpointName = comElementString.Trim();
        connectionDataEx1.COMElement = comElementString.Trim();
        break;
      case TxPlcSimitCouplingConnectionDataEx _:
        TxPlcSimitCouplingConnectionDataEx connectionDataEx2 = data as TxPlcSimitCouplingConnectionDataEx;
        if (comElementString == null)
          break;
        connectionDataEx2.EndpointName = comElementString.Trim();
        connectionDataEx2.COMElement = comElementString.Trim();
        break;
      case TxPlcUserDefinedConnectionDataEx _:
        TxPlcUserDefinedConnectionDataEx connectionDataEx3 = data as TxPlcUserDefinedConnectionDataEx;
        if (comElementString == null)
          break;
        connectionDataEx3.EndpointName = comElementString.Trim();
        connectionDataEx3.COMElement = comElementString.Trim();
        break;
    }
  }

  internal static int GetInstanceTimeoutFromData(ITxPlcExternalConnectionDataEx data)
  {
    return data is TxPlcSimAdvConnectionDataEx ? (data as TxPlcSimAdvConnectionDataEx).InstanceTimeout : 0;
  }

  internal string FormatEndpointUrlToIP(string url)
  {
    if (url.Equals("localhost") || url.Equals("local"))
      url = "";
    try
    {
      return Dns.Resolve(url).AddressList[0].ToString();
    }
    catch (SocketException ex)
    {
      if (ex.SocketErrorCode != SocketError.HostNotFound)
        throw ex;
      return url;
    }
  }

  internal bool IsPlcSimAdvancedConnectionExists(ITxPlcExternalConnectionDataEx data)
  {
    bool flag = false;
    if (data is TxPlcSimAdvConnectionDataEx)
      flag = this.m_plcimAdvancedConnctionMap.ContainsKey(this.formatPlcismAdvancedKey(data as TxPlcSimAdvConnectionDataEx));
    return flag;
  }

  internal bool IsWinModConnectionExists(ITxPlcExternalConnectionDataEx data)
  {
    bool flag = false;
    if (data is TxPlcWinModConnectionDataEx)
      flag = this.m_winModConnctionMap.ContainsKey(this.formatWinModKey(data as TxPlcWinModConnectionDataEx));
    return flag;
  }

  internal bool IsSimitCouplingConnectionExists(ITxPlcExternalConnectionDataEx data)
  {
    bool flag = false;
    if (data is TxPlcSimitCouplingConnectionDataEx)
      flag = this.m_simitCouplingConnectionMap.ContainsKey(this.formatSimitCouplingKey(data as TxPlcSimitCouplingConnectionDataEx));
    return flag;
  }

  internal bool IsUserDefinedConnectionExists(ITxPlcExternalConnectionDataEx data)
  {
    bool flag = false;
    if (data is TxPlcUserDefinedConnectionDataEx)
      flag = this.m_userDefinedConnectionMap.ContainsKey(this.formatUserDefinedKey(data as TxPlcUserDefinedConnectionDataEx));
    return flag;
  }

  internal static void SetOperatingModeToData(int mode, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return;
    (data as TxPlcSimAdvConnectionDataEx).OperatingMode = mode;
  }

  internal static int GetOperatingModeFromData(ITxPlcExternalConnectionDataEx data)
  {
    return data is TxPlcSimAdvConnectionDataEx ? (data as TxPlcSimAdvConnectionDataEx).OperatingMode : 0;
  }

  internal static void SetTagAccessModeToData(int mode, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return;
    (data as TxPlcSimAdvConnectionDataEx).TagAccessMode = mode;
  }

  internal static int GetTagAccessModeFromData(ITxPlcExternalConnectionDataEx data)
  {
    return data is TxPlcSimAdvConnectionDataEx ? (data as TxPlcSimAdvConnectionDataEx).TagAccessMode : 0;
  }

  internal static int GetCycleTimeOutFromData(ITxPlcExternalConnectionDataEx data)
  {
    return data is TxPlcSimAdvConnectionDataEx ? (data as TxPlcSimAdvConnectionDataEx).CycleTimeOut : 0;
  }

  internal static void SetCycleTimeOutFromData(int timeOut, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return;
    (data as TxPlcSimAdvConnectionDataEx).CycleTimeOut = timeOut;
  }

  internal static int GetWinModTimeOutFromData(ITxPlcExternalConnectionDataEx data)
  {
    return data is TxPlcWinModConnectionDataEx ? (data as TxPlcWinModConnectionDataEx).TimeOut : 0;
  }

  internal static void SetWinModTimeOutFromData(int timeOut, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcWinModConnectionDataEx))
      return;
    (data as TxPlcWinModConnectionDataEx).TimeOut = timeOut;
  }

  internal static string GetTagAccessFromData(ITxPlcExternalConnectionDataEx data)
  {
    string tagAccessFromData1 = "N\\A";
    if (!(data is TxPlcSimAdvConnectionDataEx))
      return tagAccessFromData1;
    string tagAccessFromData2;
    switch ((data as TxPlcSimAdvConnectionDataEx).TagAccessMode)
    {
      case 0:
        tagAccessFromData2 = "IO";
        break;
      case 1:
        tagAccessFromData2 = "IOM";
        break;
      case 2:
        tagAccessFromData2 = "IODB";
        break;
      case 3:
        tagAccessFromData2 = "IOMDB";
        break;
      default:
        tagAccessFromData2 = "IO";
        break;
    }
    return tagAccessFromData2;
  }

  internal static void SetTagAccessToData(string tagAccess, ITxPlcExternalConnectionDataEx data)
  {
    if (!(data is TxPlcSimAdvConnectionDataEx) || !(data is TxPlcSimAdvConnectionDataEx connectionDataEx))
      return;
    switch (tagAccess)
    {
      case "IO":
        connectionDataEx.TagAccessMode = 0;
        break;
      case "IOM":
        connectionDataEx.TagAccessMode = 1;
        break;
      case "IODB":
        connectionDataEx.TagAccessMode = 2;
        break;
      case "IOMDB":
        connectionDataEx.TagAccessMode = 3;
        break;
      default:
        connectionDataEx.TagAccessMode = 0;
        break;
    }
  }

  private void RegisterForEvents()
  {
  }

  private void UnregisterForEvents()
  {
  }

  internal enum eConnectionDataFormat
  {
    Grid,
    Export,
    Edit,
  }

  internal enum eSetConnectionDataFailiureReason
  {
    None,
    DuplicatedName,
    DuplicatedKey,
  }

  public enum eCreateConnectionFailiureReason
  {
    None,
    DuplicatedName,
    DuplicatedKey,
  }

  [Flags]
  private enum eConnectionDataFilterFlags
  {
    None = 0,
    Name = 1,
    Type = 2,
    Server = 4,
    ItemHeader = 8,
    MapSignalsBy = 16, // 0x00000010
    NameSpaceIndex = 32, // 0x00000020
    All = NameSpaceIndex | MapSignalsBy | ItemHeader | Server | Type | Name, // 0x0000003F
  }

  public class ImportOutputParams
  {
    internal readonly bool ImportFailed;
    internal readonly string FilePath;
    internal readonly List<string> Notifications;
    internal readonly List<string> Warnings;
    internal readonly List<string> Errors;
    internal readonly List<CApECExternalConnectionNode> ImportedNodes;
    internal readonly List<CApECExternalConnectionNode> ModifiedNodes;

    internal ImportOutputParams(CApECExcelImportParams excelParams)
    {
      this.ImportFailed = excelParams.ImportFailed;
      this.FilePath = excelParams.FilePath;
      this.Notifications = excelParams.Notifications != null ? new List<string>((IEnumerable<string>) excelParams.Notifications) : (List<string>) null;
      this.Warnings = excelParams.Warnings != null ? new List<string>((IEnumerable<string>) excelParams.Warnings) : (List<string>) null;
      this.Errors = excelParams.Errors != null ? new List<string>((IEnumerable<string>) excelParams.Errors) : (List<string>) null;
    }

    internal ImportOutputParams(CApECExcelImportParams excelParams, List<string> postImportErrors)
    {
      this.ImportFailed = excelParams.ImportFailed;
      this.FilePath = excelParams.FilePath;
      this.Notifications = excelParams.Notifications != null ? new List<string>((IEnumerable<string>) excelParams.Notifications) : (List<string>) null;
      this.Warnings = excelParams.Warnings != null ? new List<string>((IEnumerable<string>) excelParams.Warnings) : (List<string>) null;
      this.Errors = excelParams.Errors != null ? new List<string>((IEnumerable<string>) excelParams.Errors) : (List<string>) null;
      if (postImportErrors == null)
        return;
      this.Errors.AddRange((IEnumerable<string>) postImportErrors);
    }

    internal ImportOutputParams(
      CApECExcelImportParams excelParams,
      List<CApECExternalConnectionNode> importedNodes,
      List<CApECExternalConnectionNode> modifiedNodes)
    {
      this.ImportFailed = excelParams.ImportFailed;
      this.FilePath = excelParams.FilePath;
      this.Notifications = excelParams.Notifications != null ? new List<string>((IEnumerable<string>) excelParams.Notifications) : (List<string>) null;
      this.Warnings = excelParams.Warnings != null ? new List<string>((IEnumerable<string>) excelParams.Warnings) : (List<string>) null;
      this.Errors = excelParams.Errors != null ? new List<string>((IEnumerable<string>) excelParams.Errors) : (List<string>) null;
      this.ImportedNodes = importedNodes;
      this.ModifiedNodes = modifiedNodes;
    }
  }
}
